<template>
	<view>
		<view class="titlemodify" style="border-bottom: 0; position: relative;">
			<text class="all_text_title">附件上传</text>
			<l-file ref="lFile" @up-success="onSuccess"></l-file>
			<view style="position: absolute;top: 0; left: 177rpx; z-index:99" v-if="isSubmit" @click="handleUpLoad">
				<image src="../static/firm/icon_sc.png" style="width: 25rpx; height: 19rpx;"></image>
				<text style="font-size: 20rpx; color: #128BF1;margin-left: 10rpx;">
					点击上传文件
				</text>
			</view>
			
			<view ref="aaaa" class="upLoadFileWzh" style="border-bottom: 0;position: relative;" v-for="item in fileList"
				:key="item.url">
				<view class="left" @click="checkDetails(item)">
					<image src="../static/know/PDF.png" style="width: 40rpx; height: 48rpx;display: block;"></image>
					<view class="file_name">{{ item.name }}</view>
				</view>
				<uni-icons v-if="isSubmit" @click.stop="handleRemoveFile(item)" type="close" color="#eee" size="20">
				</uni-icons>
			</view>
			<view v-if="startUP" style="margin-top: 20rpx;">
				<u-line-progress :percentage="percentage_num" activeColor="#40A0F2"></u-line-progress>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'upload-file',
		data() {
			return {
				fileList: [],
				token: '',
				member_id: '',
				company_id: '',
				qiniu_token:'',
				
				percentage_num:'',//进度条数值
				startUP:false,//是否显示上传进度条
			};
		},
		props: ['imgList', 'isSubmit', 'detailsImgList'],
		created() {
			this.token = uni.getStorageSync('btlh_process_token') || '';
			this.member_id = uni.getStorageSync('btlh_process_member_id') || '';
			// console.log('文件上传组件的merid',this.member_id)
			this.company_id = uni.getStorageSync('bthl_process_LoginCompanyId') || '';
			if (this.imgList) {
				console.log('组件的imgList', this.imgList);
				this.imgList.forEach(item => {
					this.fileList.push(item);
				});
			}
			console.log('created (文件上传组件的--imgList1)', this.imgList);
		},
		mounted() {
			if (this.imgList) {
				console.log('mounted (文件上传组件的--imgList2)', this.imgList, 'fileList', this.fileList);
				/* this.imgList.forEach(item => {
					this.fileList.push(item);
					console.log('item----------'+item.index)
				}); */
			}

			console.log('mounted (文件上传组件的--imgList3)', this.imgList);
		},
		watch: {
			imgList(val, oldVal) {
				if (val) {
					console.log('va2222222222', val)
					this.fileList = val;
					// 去掉文件名的前缀
					for (var i = 0; i < this.fileList.length; i++) {
						this.fileList[i].name = this.fileList[i].name.replace('control/mobile/','')
					}
				}
			},
			detailsImgList(val, oldVal) {
				console.log('oldVal', oldVal)
				if (val) {
					this.detailsImgList = val;
				}
			}
		},
		methods: {
			toReport(path) {
				path = path || 'http.......slfjlf.pdf';
				let first = path.lastIndexOf('.'); //取到文件名开始到最后一个点的长度
				let suffixName = path.substring(first, path.length); //截取获得后缀名
				uni.showLoading({
					title: '加载中，请稍后~'
				});
				const fs = uni.getFileSystemManager();
				// 获取本地缓存文件清空，防止缓存过多预览失败
				fs.readdir({
					dirPath: wx.env.USER_DATA_PATH,
					success: res => {
						if (res.files && res.files.length > 0) {
							res.files.forEach(item => {
								fs.unlink({
									filePath: wx.env.USER_DATA_PATH + '/' + item
								});
							});
							this.openDocument(path, suffixName);
						} else {
							this.openDocument(path, suffixName);
						}
					}
				});
			},
			openDocument(path, suffixName) {
				uni.downloadFile({
					url: path,
					filePath: wx.env.USER_DATA_PATH + '/' + +suffixName,
					success: res => {
						uni.hideLoading();
						console.log('准备预览');
						console.log(res);
						uni.openDocument({
							showMenu: true,
							filePath: res.filePath
						});
					},
					fail: res => {
						uni.hideLoading();
						console.log(res);
					}
				});
			},
			// 预览文件
			checkDetails(item) {
				console.log(item)
				 const regWebsit = /(https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
				 let fileURl = '';
				        if (regWebsit.test(item.url)) {
							fileURl = item.url;
				        } else {
						  fileURl = item.url.replace("http:", "https:");
				        }

				
				if (item.type == 'doc' || item.type == 'xls' || item.type == 'ppt' || item.type == 'pdf' || item.type ==
					'docx' || item.type == 'xlsx' || item.type == 'pptx' || item.type == 'file') {
						uni.showLoading({
							title:'正在加载文档...'
						})
					console.log('if')
					uni.downloadFile({
						url: fileURl,
						success: (res) => {
							uni.hideLoading();
							var filePath = res.tempFilePath;
							uni.openDocument({
								filePath: filePath,
								success: (res) => {
									console.log('打开文档成功');
								}
							});
						},
						fail: () => {
							uni.hideLoading()
						}
					});
				} else {
					console.log('else')
					uni.navigateTo({
						url: '/pages/know/webVIew?src=' + fileURl
					})
				}
				/* uni.downloadFile({
					url: item.url, //仅为测试接口，并非真实的
					success: function(res) {
						// console.log(res)
						// return
						var postf1 = item.type;
						var filePath = res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							fileType: postf1,
							success: function(res) {
								console.log('预览res', res);
								uni.hideLoading();
							},
							fail: function(res) {
								console.log('fail萨达的萨萨达萨达萨');
								console.log(res);
								uni.hideLoading();
							},
							complete(res) {
								console.log(res);
								console.log('预览rescccccc', res);
								uni.hideLoading();
							}
						});
					},
					fail: function(res) {
						console.log('fail');
						console.log(res);
					},
					complete: function(res) {
						console.log('complete');
						console.log(res);
					}
				}); */
			},
			// 获取七牛云token
			async getQiniuToken() {
				const {
					data: res
				} = await this.$myRequest({
					url: 'Qiniu/qiniuToken',
					method: 'GET',
					data: {
						member_id: this.member_id,
						token: this.token,
					}
				});
				this.qiniu_token = res;
				console.log(res)
			},
			// 文件上传
			handleUpLoad() {
				// console.log('ref', this.$refs);
				this.getQiniuToken();
				
				uni.showModal({
					title:'提示',
					content:'选择上传图片或文件',
					cancelText:'文件',
					confirmText:'图片',
					success: (res)=> {
					        if (res.confirm) {
					            console.log('用户点击图片');
								var that = this;
								uni.chooseImage({
									count: 6, // 最多可以选择的图片张数，默认9
									sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
									sourceType: ['album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
									success: res => {
										uni.showLoading({
											title:'正在上传图片...',
											mask:true
										})
										const tempFilePaths = res.tempFilePaths;
										console.log('tempFilePaths-----' + tempFilePaths)
										tempFilePaths.forEach(item => {
											uni.uploadFile({
												// url: 'https://control.sxpz.vip/index.php/AppApi/User/uploadImg',
												// filePath: item,
												// name: 'file',
												// formData: {
												// 	member_id: this.member_id,
												// 	token: this.token
												// },
												
												url: 'https://up-z2.qiniup.com',
												filePath: item,
												name: 'file',
												formData: {
													token: this.qiniu_token,
													key:'control/mobile/' + item
												},
												success: uploadFileRes => {
													uni.hideLoading();
													const result = JSON.parse(uploadFileRes.data).key;
													// console.log('uploadFileRes-----' + result)
													// console.log('result---------' + result.datas.img_url)
													// let last = result.datas.img_url.lastIndexOf('/');
													
													// this.fileList.push({
													// 	name: result.datas.img_url.slice(last + 1),
													// 	type: 'png',
													// 	url: result.datas.img_url
													// });
													// this.$emit('my-upload-change', this.fileList);
													this.fileList.push({
														name: result,
														type: 'png',
														url: 'https://qiniu.sxpz.vip/' + result
														
													});
													this.$emit('my-upload-change', this.fileList);
													
													uni.showToast({
														title:'上传成功'
													})
												},
												fail: () => {
													uni.hideLoading();
														uni.showToast({
															title:'上传失败',
															icon:'none'
														})
												}
											});
										});
									},
									
								});
								
					        } else if (res.cancel) {
					            console.log('用户点击文件');
								
								// #ifdef MP-WEIXIN
								wx.chooseMessageFile({
									count: 1,
									type: 'all',
									success: ({tempFiles}) => {
										console.log(tempFiles)
										uni.showLoading({
											title:'正在上传文件...',
											mask:true
										})
										this.startUP = true;
										// let timestamp=new Date().getTime();
										// let nowTime = new Date(parseInt(timestamp)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
										 let timestamp = Date.parse(new Date());  
										    timestamp = timestamp / 1000;  
										    console.log("当前时间戳为：" + timestamp); 
										let	randomNum = (Math.random() * 1000).toFixed(0);
										console.log("当前随机数：" + randomNum); 
										
										tempFiles.forEach(item => {
											let a = item.name.lastIndexOf('.');
											let b = item.name.slice(0,a);
											let c = item.name.slice(a);
											var uploadTask = uni.uploadFile({
												url: 'https://up-z2.qiniup.com',
												filePath: item.path,
												name: 'file',
												formData: {
													token: this.qiniu_token,
													// key:timestamp + randomNum + item.name
													key:'control/mobile/'+ b + timestamp + randomNum + c
												},
												success: uploadFileRes => {
													
													const result = JSON.parse(uploadFileRes.data).key;
													let typeArr = item.name.split('.');
													// console.log('uploadFileRes-----' + result)
													this.fileList.push({
														name: result,
														type: typeArr[typeArr.length - 1],
														url: 'https://qiniu.sxpz.vip/' + result
														
													});
													uni.showToast({
														title:'上传成功'
													})
													this.startUP = false;
													uni.hideLoading();
													this.$emit('my-upload-change', this.fileList);
													return
												},
												fail: () => {
													uni.hideLoading();
													uni.showToast({
														title:'上传文件失败',
														icon:'none'
													})
												}
											});
											
											// 监听上传进度
											uploadTask.onProgressUpdate((res) => {
												this.percentage_num = res.progress;
													});
										});
									},
									fail:({res})=>{
										uni.hideLoading()
									}
								})
								// #endif
								
								/* this.$nextTick(function() {
									this.$refs.lFile.upload({
										// #ifdef APP-PLUS
										currentWebview: this.$mp.page.$getAppWebview(),
										// #endif
										url: 'https://control.sxpz.vip/index.php/AppApi/User/uploadImg',
										name: 'file',
										member_id: this.member_id,
										token: this.token
									});
								}) */
					        }
					    }
				})
				
			},
			onSuccess(res) {
				console.log('onSuccess---------')
				let ress = res.data;
				let fileName = res.fileName;
				if (ress.code != 200)
					return uni.showToast({
						title: ress.datas.msg,
						icon: 'none'
					});
				uni.showToast({
					title: '上传成功',
					icon: 'none'
				});
				let nameArr = ress.datas.img_url.split('/');
				let typeArr = ress.datas.img_url.split('.');
				this.fileList.push({
					name: fileName,
					type: typeArr[typeArr.length - 1],
					url: ress.datas.img_url
				});
				this.$emit('my-upload-change', this.fileList);
			},
			// 删除文件
			handleRemoveFile(val) {
				console.log('点击删除文件')
				let removeIndex = this.fileList.findIndex(item => item.url === val.url);
				console.log('删除文件' + removeIndex);
				this.fileList.splice(removeIndex, 1);
				this.$emit('my-upload-change', this.fileList);
			}
		}
	};
</script>

<style lang="scss">
	/* 文件 */
	.titlemodify {
		width: 690rpx;
		margin-top: 44rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #333333;
		border-bottom: 1rpx solid #e3e3e3;
	}

	.upLoadFileWzh {
		padding-left: 20rpx;
		margin-top: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.file_name {
		font-size: 26rpx;
		font-family: PingFang SC;
		font-weight: 500;
		width: 490rpx;
		overflow: hidden;
		/*超出部分隐藏*/
		white-space: nowrap;
		/*不换行*/
		text-overflow: ellipsis;
		/*超出部分文字以...显示*/
		color: #999999;
		margin-left: 30rpx;
	}

	.upLoadFileWzh .left {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
</style>
